<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    @ok="handleOk"
    :okButtonProps="{}"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <ContractsForm ref="registerForm" @ok="submitCallback" :formDisabled="disableSubmit" :formBpm="false" :record="currentRecord" />

    <!-- 详情模态框中的操作按钮 -->
    <div v-if="disableSubmit && currentRecord" class="detail-actions">
      <a-divider />
      <div class="action-buttons">
        <!-- 只有待审批状态（状态值为'1'或空）才显示审批按钮 -->
        <a-button
          v-if="currentRecord.approveStatus === '1' || currentRecord.approveStatus === ''"
          type="primary"
          @click="handleApprove"
          style="margin-right: 8px"
        >
          审批
        </a-button>
      </div>
    </div>
  </j-modal>
</template>


<script lang="ts" setup>
  import { ref, nextTick, defineExpose } from 'vue';
  import ContractsForm from './ContractsForm.vue';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  const title = ref<string>('');
  const width = ref<number>(800);
  const visible = ref<boolean>(false);
  const disableSubmit = ref<boolean>(false); // Internal state for form disabled status
  const registerForm = ref();
  const currentRecord = ref<any>(null);
  const emit = defineEmits(['register', 'success', 'approve']);

  /**
   * 新增
   */
  function add() {
    title.value = '新增';
    disableSubmit.value = false; // Enable form for adding
    visible.value = true;
    nextTick(() => {
      registerForm.value.add();
    });
  }

  /**
   * 编辑
   * @param record
   */
  function edit(record) {
    title.value = '编辑';
    disableSubmit.value = false; // Enable form for editing
    visible.value = true;
    currentRecord.value = record;
    nextTick(() => {
      registerForm.value.edit(record);
    });
  }

  /**
   * 详情
   * @param record
   */
  function detail(record) {
    title.value = '详情';
    disableSubmit.value = true; // Disable form for viewing details
    visible.value = true;
    currentRecord.value = record;
    nextTick(() => {
      registerForm.value.edit(record); // Use edit function, but form will be disabled
    });
  }

  /**
   * 审批事件
   */
  function handleApprove() {
    emit('approve', currentRecord.value);
  }

  /**
   * 确定按钮点击事件
   */
  function handleOk() {
    registerForm.value.submitForm();
  }

  /**
   * form保存回调事件
   */
  function submitCallback() {
    handleCancel();
    emit('success');
  }

  /**
   * 取消按钮回调事件
   */
  function handleCancel() {
    visible.value = false;
  }

  defineExpose({
    add,
    edit,
    detail, // Expose the new detail function
    handleCancel,
  });
</script>

<style>
  /**隐藏样式-modal确定按钮 */
  .jee-hidden {
    display: none !important;
  }
</style>
<style lang="less" scoped>
  .detail-actions {
    margin-top: 16px;

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 8px;
    }
  }
</style>
